<script setup>
import { ref } from 'vue'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import { useExperimentStore } from '@/stores/experimentStore'
import { useTokenStore } from '@/stores/tokens'
import { ElMessage } from 'element-plus'
import api from '@/api/request'
import { useRouter } from 'vue-router'

const experimentStore = useExperimentStore()
const teamNameStore = useExperimentStore()
const tokenStore = useTokenStore()
const router = useRouter()

const activeIndex = ref('1')
const dialogVisible = ref(false)
const saveData = ref(false)
const dialogNewExp = ref(false)
const formLabelWidth = '120px'

const newExperimentData = ref({
  experimentName: '',
  teamName: ''
})

// 方法定义
const cancelLogout = () => {
  dialogVisible.value = false
}

const handleLogout = () => {
  // 登出逻辑
}

import { nextTick } from 'vue'

const selectHistoryExperiment = async (experiment) => {
  console.log('选中的实验名称:', experiment.name)

  try {
    // 调用 API 获取数据
    await experimentStore.fetchHistoryExperiments(experiment.name)

    // 等待 Vue 更新
    await nextTick()

    console.log(
      '⚡ nextTick 检查 historyExperiments:',
      experimentStore.historyExperiments
    )

    // **不使用 `.value` 直接访问**
    const experiments = experimentStore.historyExperiments

    if (!experiments) {
      console.error(
        '❌ 实验数据未正确加载, experimentStore.historyExperiments 可能为 undefined'
      )
      ElMessage.error('实验数据加载失败，请重试')
      return
    }

    // ✅ 存储到全局状态
    experimentStore.collectedExperiments = experiments
    console.log('✅ 历史实验数据已更新:', experiments)

    // ✅ 页面跳转
    router.push({ path: '/result' })
  } catch (error) {
    console.error('❌ 请求失败:', error)
    ElMessage.error('请求失败，请检查网络连接或稍后重试')
  }
}

const confirmNewExperiment = async () => {
  if (
    !newExperimentData.value.experimentName ||
    !newExperimentData.value.teamName
  ) {
    ElMessage.error('实验名称和团队名称不能为空')
    return
  }

  try {
    const response = await api.post(
      '/new',
      {
        experimentName: newExperimentData.value.experimentName,
        teamName: newExperimentData.value.teamName
      },
      {
        headers: {
          'Content-Type': 'application/json',
          token: tokenStore.token
        }
      }
    )

    if (response.status === 200) {
      ElMessage.success('实验创建成功')
      dialogNewExp.value = false

      // 更新 store 中的实验名称和团队
      experimentStore.collectedExperiments.experimentName =
        newExperimentData.value.experimentName
      teamNameStore.teamName = newExperimentData.value.teamName

      // 清空输入框
      newExperimentData.value.experimentName = ''
      newExperimentData.value.teamName = ''
    } else {
      ElMessage.error('实验创建失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('请求失败，请重试')
  }
}
</script>
<template>
  <el-header>
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      background-color="lightblue"
      text-color="#fff"
      active-text-color="#ffd04b"
    >
      <!-- 退出确认对话框 -->
      <el-dialog title="确认退出" v-model="dialogVisible" width="30%">
        <span>您确定要退出登录吗？</span>
        <br />
        <el-checkbox v-model="saveData"> 是否需要保存当前数据？ </el-checkbox>
        <template #footer>
          <el-button @click="cancelLogout">取消</el-button>
          <el-button type="primary" @click="handleLogout"> 确定退出 </el-button>
        </template>
      </el-dialog>

      <el-dropdown>
        <span
          class="history_text"
          style="float: right; font-size: large; color: #101010"
        >
          历史实验
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="experiment in experimentStore.historyExperiments"
              :key="experiment.id"
              @click="selectHistoryExperiment(experiment)"
            >
              {{ experiment.name }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-menu-item
        index="4"
        style="font-size: large; color: #101010"
        @click="dialogNewExp = true"
        class="right_menu"
      >
        <el-icon><Plus /></el-icon>
        新建实验
      </el-menu-item>
    </el-menu>

    <el-dialog v-model="dialogNewExp" title="新建实验" width="500">
      <el-form>
        <el-form-item label="实验名称" :label-width="formLabelWidth">
          <el-input v-model="newExperimentData.experimentName"></el-input>
        </el-form-item>
        <el-form-item label="选择团队" :label-width="formLabelWidth">
          <el-select
            v-model="newExperimentData.teamName"
            placeholder="请选择团队"
          >
            <el-option
              v-for="item in teamNameStore.teamOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogNewExp = false">取消</el-button>
          <el-button type="primary" @click="confirmNewExperiment">
            确认新建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-header>
</template>

<style lang="scss" scoped>
.el-menu-demo {
  border: none;
  background: linear-gradient(to right, #409eff, #67c23a);
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0 20px;

  .el-menu-item {
    color: #000000 !important;
    font-weight: 500;
    margin-left: 20px;

    &:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }
  }
}

.history_text {
  color: #fff;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.right_menu {
  margin-left: auto;
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
  display: flex;
  align-items: center;
}

.el-header {
  --el-header-padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
